const Draggabilly = require('draggabilly');
let draggies = [];

// pg5-jp: { left: 38%, top: 36%, width: 24%, h2w: 589/217->668/200 }
let stage = 0;
const target = document.querySelector('.pg5-jp');
const clientH = document.documentElement.clientHeight;
const clientW = document.documentElement.clientWidth;
const draggable = {
  width: {
    min: Math.round(0.38 * clientW),
    max: Math.round((0.38 + 0.24) * clientW),
  },
  height: {
    min: Math.round(0.36 * clientH),
    max: Math.round(0.24 * clientW * 668 / 200 + 0.36 * clientH),
  },
};

// pg8-3: { sector: 12, win: -15deg, lost: 15deg }
let timer = null;
let degs = 3600;

let isTouched = false;
const imgList = [ 'images/2-4.png', 'images/3-4.png', 'images/4-4.png' ];

document.addEventListener('DOMContentLoaded', () => {
  // 1. draggable
  draggies = [].map.call(document.querySelectorAll('.draggable'),
    draggie => {
      const _draggie = new Draggabilly(draggie, {
        containment: '.container-draggie',
      });
      _draggie.on('dragMove', (e, p) => {
        if ( p.clientX > draggable.width.min
          && p.clientX < draggable.width.max
          && p.clientY > draggable.height.min
          && p.clientY < draggable.height.max ) {
            if (!e.target.classList.contains('is-end')) {
              target.classList.add(`is-stage-${++stage}`);
              target.src = target.src.replace(/stage\/\d/, `stage/${stage}`);
            }
            e.target.classList.add('is-end');
          }
      });
      return _draggie;
    });

  // 2. scrapeable
  [].map.call(document.querySelectorAll('.scrapeable canvas'),
    (scrape, idx) => {
      const ctx = scrape.getContext('2d');
      const img = new Image();
      img.src = imgList[idx];
      img.onload = () => {
        ctx.drawImage(img, 0, 0, scrape.width, scrape.height);
      };
      
      ['touchstart', 'touchend', 'mousedown', 'mouseup'].forEach((e, idx) =>
        scrape.addEventListener(e, evt => {
          evt.preventDefault();
          isTouched = idx % 2 === 0;
      }));
      ['touchmove', 'mousemove'].forEach(e =>
        scrape.addEventListener(e, evt => {
          evt.preventDefault();
          if (isTouched) {
            if (evt.changedTouches) evt = evt.changedTouches[evt.changedTouches.length - 1];
            const rect = scrape.getBoundingClientRect(); 
            ctx.beginPath();
            ctx.arc((evt.clientX - rect.left) * scrape.width / rect.width,
                    (evt.clientY - rect.top) * scrape.height / rect.height,
                    10, 0, Math.PI * 2);
            ctx.fill();
            ctx.globalCompositeOperation = 'destination-out';
          }
      }));
    }
  );
});

// 3. turntable
window.turntable = (
  isWin = false,
  cb = () => {}, // callback
  duration = 8, // s
  increment = 3600 // deg
) => {
  const el = document.getElementById('turntable');
  el.style.transitionDuration = `${duration}s`;
  el.classList.add('is-active');
   if (!timer) {
     timer = setTimeout(() => {
      degs += increment;
      el.style.transform = `rotateZ(${ isWin ? degs - 15  : degs + 15 }deg)`;
      setTimeout(() => {
        timer = null;
        clearTimeout(timer);
        cb();
      }, duration * 1000 + 500);
    }, 500);
   }
};